package com.face.controller;

import com.face.common.Result;
import com.face.common.ResultCode;
import com.face.common.UserInfo;
import com.face.entity.Shop;
import com.face.service.AccountService;
import com.face.service.ShopService;
import com.face.util.CookieUtil;
import com.face.util.JwtUtil;
import com.face.vo.ShopInfoVO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.lang.Nullable;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@RestController
@RequestMapping("/shop")
public class ShopController {

    @Autowired
    private ShopService shopService;
    @Autowired
    private AccountService accountService;

    @PostMapping
    public Result updateShopInfo(@RequestBody Shop shop) {
        shopService.update(shop);
        accountService.updateStatus(shop.getShopId(), 3);
        return Result.success();
    }

    @PutMapping
    public Result updateShopInfo(@Nullable @CookieValue("Token")String token, @RequestBody Shop shop, HttpServletRequest request, HttpServletResponse response){
        if (StringUtils.isBlank(token)) {
            return Result.failure(ResultCode.UNANTH);
        }
        try {
            UserInfo userInfo = JwtUtil.parseJWT(token);
            shop.setShopId(userInfo.getShopId());
            shopService.update(shop);
            accountService.updateStatusByUsername(userInfo.getUsername(), 3);
            userInfo.setStatus(3);
            token = JwtUtil.createJWT(userInfo, "face", 30 * 60 * 1000);
            CookieUtil.setCookie(request, response, "Token", token, 30 * 60 * 1000, true, true);
            return Result.success();
        } catch (Exception e) {
            return Result.failure(ResultCode.UNANTH);
        }
    }

    @GetMapping("/{activeCode}")
    public Result findShopByActiveCode(@PathVariable String activeCode){
        Shop shop = shopService.findShopByActiveCode(activeCode);
        accountService.active(activeCode);
        if (shop == null) {
            return Result.failure(ResultCode.LINK_FAILURE);
        }
        return Result.success(shop);
    }

    @GetMapping("/info/{shopId}")
    public Result findShopInfoById(@PathVariable String shopId) {
        ShopInfoVO shopInfoVO = shopService.findShopInfoById(shopId);
        return Result.success(shopInfoVO);
    }

}
